package com.osfw.system.cotroller.manage;

import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.PageInfo;
import com.osfw.framework.annotation.Log;
import com.osfw.framework.annotation.RepeatSubmit;
import com.osfw.framework.constants.Constants;
import com.osfw.framework.core.domain.RestfulResult;
import com.osfw.framework.enums.BusinessType;
import com.osfw.framework.utils.DateUtils;
import com.osfw.framework.utils.PasswordUtil;
import com.osfw.framework.utils.StringUtils;
import com.osfw.framework.utils.text.Convert;
import com.osfw.framework.core.controller.BaseController;
import com.osfw.framework.web.service.PasswordService;
import com.osfw.system.entity.manage.SysDept;
import com.osfw.system.entity.manage.SysRole;
import com.osfw.system.entity.manage.SysUser;
import com.osfw.system.service.manage.ISysDeptService;
import com.osfw.system.service.manage.ISysRoleService;
import com.osfw.system.service.manage.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 */
@Controller
@RequestMapping("/osfw/system/manage/user")
public class SysUserController extends BaseController {
    private String prefix = "osfw/system/manage/user";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private ISysDeptService deptService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public PageInfo list(SysUser user) {
        startPage(SysUser.class);
        List<SysUser> list = userService.selectUserList(user);
        return getPageInfo(list);
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public RestfulResult addSave(@Validated SysUser user) {
        roleService.checkRoleDataScope(user.getRoleIds());
        if (Constants.NOT_UNIQUE.equals(userService.checkLoginNameUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && Constants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && Constants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(PasswordUtil.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setPwdUpdateDate(DateUtils.getNowDate());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        userService.checkUserDataScope(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("sysUser", userService.selectUserById(userId));
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return prefix + "/edit";
    }

    /**
     * 查询用户详细
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/view/{userId}")
    public String view(@PathVariable("userId") Long userId, ModelMap mmap) {
        userService.checkUserDataScope(userId);
        mmap.put("sysUser", userService.selectUserById(userId));
        mmap.put("roleGroup", userService.selectUserRoleGroup(userId));
        return prefix + "/view";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public RestfulResult editSave(@Validated SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (Constants.NOT_UNIQUE.equals(userService.checkLoginNameUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && Constants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && Constants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(userService.updateUser(user));
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    @RepeatSubmit
    public RestfulResult resetPwdSave(SysUser user) {
        userService.checkUserAllowed(user);
        SysUser sysUser = userService.selectUserById(user.getUserId());
        user.setSalt(PasswordUtil.randomSalt());
        user.setPassword(PasswordUtil.encryptPassword(sysUser.getLoginName(), user.getPassword(), user.getSalt()));
        user.setPwdUpdateDate(null);
        if (userService.resetUserPwd(user)) {
            if (getUserId().longValue() == user.getUserId().longValue()) {
                StpUtil.getSession().set("user", userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    @GetMapping("/editPwd")
    public String resetPwd(ModelMap mmap) {
        SysUser user = getSysUser();
        mmap.put("user", userService.selectUserById(user.getUserId()));
        return prefix + "/editPwd";
    }

    @PostMapping("/checkPassword")
    @ResponseBody
    public String checkPassword(String password) {
        SysUser user = getSysUser();
        if (passwordService.matches(user, password)) {
            return Constants.CORRECT;
        }
        return Constants.NOT_CORRECT;
    }

    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    @PostMapping("/editPwd")
    @ResponseBody
    @RepeatSubmit
    public RestfulResult editPwd(String oldPassword, String newPassword) {
        SysUser user = getSysUser();
        if (StringUtils.isNotEmpty(newPassword) && passwordService.matches(user, oldPassword)) {
            user.setSalt(PasswordUtil.randomSalt());
            user.setPassword(passwordService.encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
            user.setPwdUpdateDate(new Date());
            if (userService.resetUserPwd(user)) {
                StpUtil.getSession().set("user", userService.selectUserById(user.getUserId()));
                return success();
            }
            return error();
        } else {
            return error("修改密码失败，旧密码错误");
        }
    }

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{userId}")
    public String authRole(@PathVariable("userId") Long userId, ModelMap mmap) {
        SysUser user = userService.selectUserById(userId);
        // 获取用户所属的角色列表
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("sysUser", user);
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return prefix + "/authRole";
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public RestfulResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public RestfulResult remove(String ids) {
        if (ArrayUtils.contains(Convert.toLongArray(ids), getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(ids));
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user) {
        return userService.checkLoginNameUnique(user);
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user) {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public RestfulResult changeStatus(SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        return toAjax(userService.changeStatus(user));
    }

    /**
     * 方法描述 1.跳转至选择用户页面
     *
     * @param sysUser   用户信息
     * @param elementId 调用控件id
     * @param isExcludeSelected 当userIds不为空时，是排除已选择还是默认选中，0-选中已选（默认），1-排除已选
     */
    @GetMapping("/selectUsers")
    public String selectUsers(SysUser sysUser, String selectType, String elementId, String isExcludeSelected, ModelMap mmap) {
        // 获取当前登录人员
        SysUser user = getSysUser();
        if (sysUser.getDeptId() != null) {
            // 获取部门
            SysDept sysDept = deptService.selectDeptById(sysUser.getDeptId());
            // 默认查询人员所属部门
            if (sysDept != null) {
                sysUser.setDeptId(sysDept.getDeptId());
                sysUser.setDeptName(sysDept.getDeptName());
            }
        } else if (user.getDeptId() != null) {
            // 获取部门
            SysDept sysDept = deptService.selectDeptById(user.getDeptId());
            // 默认查询人员所属部门
            if (sysDept != null) {
                user.setDeptId(sysDept.getDeptId());
                user.setDeptName(sysDept.getDeptName());
            }
        }
        // 获取已选择人员信息集合
        if (sysUser.getUserIds() != null && sysUser.getUserIds().length != 0) {
            // 获取已选择库中已保存的人员
            List<SysUser> userSelected = userService.selectUserListByIds(sysUser);
            mmap.put("userSelected", userSelected);
        } else {
            mmap.put("userSelected", null);
        }
        mmap.put("sysUser", sysUser);
        mmap.put("selectType", selectType);
        mmap.put("elementId", elementId);
        mmap.put("isExcludeSelected", isExcludeSelected);
        return prefix + "/selectUsers";
    }

    /**
     * 方法描述 2.查询待选择用户列表（分页）
     *
     * @param sysUser 用户信息
     * @return TableDataInfo
     */
    @PostMapping("/userList")
    @ResponseBody
    public PageInfo userList(SysUser sysUser) {
        startPage(SysUser.class);
        sysUser.setDelFlag("0");
        List<SysUser> list = userService.selectUserListAll(sysUser);
        return getPageInfo(list);
    }

    /**
     * 方法描述 3.查询待选择用户列表（不分页）
     *
     * @param sysUser 用户信息
     */
    @PostMapping("/userListAll")
    @ResponseBody
    public List<SysUser> userListAll(SysUser sysUser) {
        sysUser.setDelFlag("0");
        return userService.selectUserListAll(sysUser);
    }

}